<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RichTextEditor from '@/components/RichTextEditor.vue'
import {
  fetchUserPage,
  getUserById,
  createUser,
  updateUser,
  deleteUser,
  deleteUserBatch,
} from '@/api/user'

const loading = ref(false)
const pageNo = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])

const query = reactive({ uname: '', email: '', status: '' })

const multipleSelection = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const isEdit = ref(false)
const formRef = ref()
const form = reactive({
  id: null,
  uname: '',
  password: '',
  phone: '',
  email: '',
  role: 'USER',
  status: 1,
  utime: new Date(),
  bio: '',
  avatarUrl: '',
})

const rules = {
  uname: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
  ],
  phone: [{ required: false, trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

function loadData() {
  loading.value = true
  fetchUserPage({
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    uname: query.uname || undefined,
    email: query.email || undefined,
    status: query.status === '' ? undefined : Number(query.status),
  })
    .then((res) => {
      if (String(res.code) === '200') {
        list.value = res.data?.records || []
        total.value = res.data?.total || 0
      } else {
        ElMessage.error(res.msg || '查询失败')
      }
    })
    .finally(() => {
      loading.value = false
    })
}

function handleQuery() {
  pageNo.value = 1
  loadData()
}

function resetQuery() {
  query.uname = ''
  query.email = ''
  query.status = ''
  handleQuery()
}

function handleSelectionChange(rows) {
  multipleSelection.value = rows || []
}

function handleAdd() {
  dialogTitle.value = '新增用户'
  isEdit.value = false
  Object.assign(form, {
    id: null,
    uname: '',
    password: '',
    phone: '',
    email: '',
    role: 'USER',
    status: 1,
    utime: new Date(),
    bio: '',
    avatarUrl: '',
  })
  dialogVisible.value = true
}

async function handleEdit(row) {
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  try {
    const res = await getUserById(row.id)
    if (String(res.code) === '200') {
      Object.assign(form, res.data || row)
    } else {
      Object.assign(form, row)
      ElMessage.warning(res.msg || '获取详情失败，已使用列表数据')
    }
  } catch (e) {
    Object.assign(form, row)
  }
  // 编辑弹窗中统一处理头像URL的回显
  form.avatarUrl = resolveStaticUrl(form.avatarUrl)
  dialogVisible.value = true
}

function submitForm() {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const payload = { ...form }
      const api = isEdit.value ? updateUser : createUser
      const res = await api(payload)
      if (String(res.code) === '200') {
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
        dialogVisible.value = false
        loadData()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (e) {}
  })
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确认删除用户“${row.uname}”吗？`, '提示', { type: 'warning' })
    const res = await deleteUser(row.id)
    if (String(res.code) === '200') {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (e) {}
}

async function handleBatchDelete() {
  const ids = multipleSelection.value.map((i) => i.id)
  if (!ids.length) return ElMessage.warning('请先选择要删除的记录')
  try {
    await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 条用户吗？`, '提示', { type: 'warning' })
    const res = await deleteUserBatch(ids)
    if (String(res.code) === '200') {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) {}
}

function handleSizeChange(size) {
  pageSize.value = size
  pageNo.value = 1
  loadData()
}

function handleCurrentChange(page) {
  pageNo.value = page
  loadData()
}

function htmlToText(html) {
  if (!html) return ''
  const div = document.createElement('div')
  div.innerHTML = html
  return (div.textContent || div.innerText || '').trim()
}

function formatDate(d) {
  if (!d) return '-'
  try {
    const date = typeof d === 'string' || typeof d === 'number' ? new Date(d) : d
    return date.toLocaleString()
  } catch (e) {
    return String(d)
  }
}

// 头像上传：通过 /api/file/upload 代理到后端，并设置鉴权头
const uploadHeaders = { Authorization: `Bearer ${localStorage.getItem('token') || ''}` }
// 静态资源前缀：可改成您的服务器IP或域名
const STATIC_BASE_URL = import.meta.env.VITE_STATIC_BASE_URL || 'http://localhost:9090/'
// 统一将文件名或相对路径转换成可访问的完整URL
function resolveStaticUrl(path) {
  if (!path) return ''
  if (/^(https?:|data:)/.test(path)) return path
  if (path.startsWith('/api/')) return path
  const base = (import.meta.env.VITE_STATIC_BASE_URL || 'http://localhost:9090/').replace(/\/+$/, '')
  const cleaned = String(path).replace(/^\/+/, '')
  return `${base}/${cleaned}`
}

function beforeAvatarUpload(file) {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) ElMessage.error('仅支持图片类型文件')
  if (!isLt2M) ElMessage.error('图片大小需小于2MB')
  return isImage && isLt2M
}

function handleAvatarSuccess(response) {
  if (response && String(response.code) === '200' && response.data) {
    // 兼容两种返回：文件名（upload.xxx.jpeg）或完整/相对URL（/upload/xxx.jpeg）
    form.avatarUrl = resolveStaticUrl(response.data)
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response?.msg || '上传失败')
  }
}

function handleAvatarError() {
  ElMessage.error('头像上传失败')
}

onMounted(loadData)
</script>

<template>
  <div class="page">
    <div class="page-header">
      <div class="title">用户管理</div>
      <div class="actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <el-card class="card" shadow="never">
      <el-form :inline="true" :model="query" class="query-form">
        <el-form-item label="用户名">
          <el-input v-model="query.uname" placeholder="支持模糊查询" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="query.email" placeholder="支持模糊查询" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable style="width: 180px">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="card" shadow="never">
      <el-table
        :data="list"
        v-loading="loading"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <!-- 新增头像列 -->
        <el-table-column label="头像" width="100">
          <template #default="{ row }">
            <el-avatar :size="48" :src="resolveStaticUrl(row.avatarUrl) || undefined">
              {{ (row.uname || '').slice(0,1) || 'U' }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="uname" label="用户名" min-width="140" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="电话" width="140" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'ADMIN' ? 'warning' : 'info'">
              {{ row.role === 'ADMIN' ? '管理员' : '用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="utime" label="注册时间" min-width="180">
          <template #default="{ row }">
            {{ formatDate(row.utime) }}
          </template>
        </el-table-column>
        <el-table-column prop="bio" label="简介" min-width="220">
          <template #default="{ row }">
            <span class="desc">{{ htmlToText(row.bio) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="pageNo"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="720px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="112px">
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="form.uname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="座机或手机" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" style="width: 180px">
            <el-option label="用户" value="USER" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" style="width: 180px">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="个人简介">
          <RichTextEditor v-model="form.bio" height="240px" />
        </el-form-item>
        <!-- 新增头像上传 -->
        <el-form-item label="头像上传">
          <el-upload
            class="avatar-uploader"
            action="/api/file/rich-text-image"
            :headers="uploadHeaders"
            name="file"
            :show-file-list="false"
            accept="image/*"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
          >
            <img v-if="form.avatarUrl" :src="resolveStaticUrl(form.avatarUrl)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="头像URL">
          <el-input v-model="form.avatarUrl" placeholder="例如 http://localhost:9090/upload.xxxx.jpeg 或 https://..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page {
  padding: 16px;
}
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.title {
  font-size: 18px;
  font-weight: 600;
}
.card {
  margin-bottom: 12px;
}
.query-form :deep(.el-form-item) {
  margin-right: 12px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
.desc {
  display: inline-block;
  max-width: 380px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/* 头像上传样式 */
.avatar-uploader {
  display: inline-block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>